<template>
    <div style="width: 600px;" class="form-box">
        <a-form :model="form" @submit="handleSubmit" class="register-box">
            <a-form-item field="name" tooltip="Please enter username" label="输入账号名">
                <a-input v-model="form.name" placeholder="请输入用户名(账号)..." />
            </a-form-item>
            <a-form-item field="post" label="密码">
                <a-input v-model="form.pwd" placeholder="请输入密码..." />
            </a-form-item>

            <div class="button-box">
                <a-button type="primary" html-type="submit" status="success">登录</a-button>

                <a-button type="primary" @click="NavtoRegister()">注册</a-button>
            </div>
        </a-form>
    </div>
</template>
  
<script>
import { reactive } from "vue";
import { Message } from '@arco-design/web-vue';
import { useStore } from 'vuex';
import router from '@/router'
import http from '../../main';

export default {
    setup() {
        const store = useStore();
        const form = reactive({
            name: "",
            pwd: "",
        });

        const NavtoRegister = () => {
            router.push({ name: "UserRegsiterView" })
        }

        const handleSubmit = (data) => {
            console.log(data.values.name)
            http.post('/users/login', {
                "name": data.values.name,
                "password": data.values.pwd
            })
                .then(resp => {
                    if (resp.data.success) {
                        Message.success({
                            content: "登录成功!",
                            closable: true
                        })
                        // 持久化jwt_token
                        localStorage.setItem('token', resp.data.data.jwtToken);

                        router.push({ name: "PostIndexView" })
                        console.log(store.state.user.is_login)
                        store.commit("UserHasLogin", resp.data.data)
                        console.log(store.state.user.is_login)
                    }
                    else {
                        Message.error({
                            content: "账号或者密码错误!",
                            closable: true
                        })
                    }
                })
                .catch(err => {
                    console.log(err)
                    Message.error({
                        content: "会话超时，请稍后重试!",
                        closable: true
                    })
                })
        };

        return {
            form,
            handleSubmit, NavtoRegister
        };
    },
};
</script>       

<style scoped>
.register-box {
    margin-top: 40px;
}

.button-box {
    display: flex;
    justify-content: space-between;
    padding-left: 125px;
}
</style>